<template>
  <div class="mainbox">
    <!-- 关闭全屏 -->
    <img
      src="@/assets/images/image_quanping_icon_close.png"
      alt=""
      class="quanping_icon_close"
      @click="toggleFullscreen"
    />
    <!-- 背景 -->
    <img src="@/assets/images/indeximage_bg.png" alt="" class="indexbg" />
    <!-- 标题 -->
    <div
      v-if="newdata"
      class="head_titlebox
    "
    >
      <img
        src="@/assets/images/image_head_title.png"
        alt=""
        class="head_title"
      />
      <span>{{ newdata.modelName }}</span>
    </div>

    <!-- footer -->
    <!-- <img
      src="@/assets/images/image_footer.png"
      alt=""
      class="footer"
      v-if="!fullscreen"
    /> -->
    <!-- 模型展示 -->
    <moDelType
      v-if="newdata"
      class="modelbox"
      :modelUrl="modelUrl"
      ref="modelbox"
      @checkedModel="checkedModel"
      :modelDrag="modelDrag"
    />
    <!-- 模型任务栏 -->
    <div class="image_qj_sqbox" v-show="!taskshow" @click="taskshow = true">
      <img
        src="@/assets/images/image_icon_zk.png"
        alt=""
        class="image_icon_zks"
      />
      <img
        src="@/assets/images/image_title_qij_shouqi.png"
        alt=""
        class="image_qj_sq"
      />
      <span>组成器件</span>
    </div>
    <div class="taskbox" v-show="taskshow">
      <!-- 关闭 -->
      <img
        src="@/assets/images/image_icon_zk.png"
        alt=""
        class="image_icon_zk"
        @click="taskshow = false"
      />
      <!-- 背景-->
      <img src="@/assets/images/image_qj_bg.png" alt="" class="image_qj_bg" />
      <!-- 标题 -->
      <div class="qjname">
        <img
          src="@/assets/images/image_title_qij_zhankai.png"
          alt=""
          class="image_qj_title"
        />
        <span>组成器件</span>
      </div>
      <div class="taskmain beautifulScroll">
        <div
          class="taskitem"
          v-for="item in modelDrag"
          :key="item.componentSign"
        >
          <div class="tool taskitem-iconbox" @click="taskidgo(item)">
            <img
              src="@/assets/images/image_qj_boder_sel.png"
              alt=""
              class="active"
              v-if="taskid != item.componentSign"
            />
            <img
              src="@/assets/images/image_qj_boder_nor.png"
              alt=""
              class="normal"
              v-if="taskid != item.componentSign"
            />
            <img
              v-if="taskid == item.componentSign"
              src="@/assets/images/image_qj_boder_sel.png"
              alt=""
            />

            <img
              :src="baseurl + item.componentCover"
              alt=""
              class="taskitem-icon"
            />
            <div class="tool taskitem-name">
              <img
                src="@/assets/images/image_qj_mingcheng_sel.png"
                alt=""
                class="active"
                v-if="taskid != item.componentSign"
              />
              <img
                src="@/assets/images/image_qj_mingcheng_nor.png"
                alt=""
                class="normal"
                v-if="taskid != item.componentSign"
              />
              <img
                v-if="taskid == item.componentSign"
                src="@/assets/images/image_qj_mingcheng_sel.png"
                alt=""
              />
              <span> {{ item.componentName }}</span>
            </div>
          </div>
          <!-- <div
            class="taskitem-name"
            
          >
           
          </div> -->
        </div>
      </div>
    </div>
    <!-- 模型功能菜单-->
    <div class="anbox">
      <img src="@/assets/images/mentbjs.png" alt="" class="mentbjs" />
      <div
        class="tool anboxitem"
        v-for="item in mentdata"
        :key="item.id"
        @click="mentfn(item.id)"
      >
        <img :src="item.src" alt="" class="active" v-if="item.id != mentid" />
        <img :src="item.srcac" alt="" class="normal" v-if="item.id != mentid" />
        <img
          :src="item.src"
          alt=""
          v-if="item.id == mentid"
          style="cursor: pointer;"
        />
        <img
          src="@/assets/images/image_caozuotishi.png"
          alt=""
          class="caozuotishi"
          v-if="tipshow && item.id == 1"
        />
        <div class="yiru_bg tiptool" v-if="item.id != 1">
          <span>{{ item.id == mentid ? item.nameac : item.name }}</span>
          <img src="@/assets/images/image_yiru_bg.png" alt="" />
        </div>
      </div>
    </div>

    <!-- 模型介绍 "-->
    <div class="modeldesbox" v-if="modeldes">
      <!-- 关闭 -->
      <img
        src="@/assets/images/image_qjsm_icon_close.png"
        alt=""
        class="icon_close"
        @click="modeldes = ''"
      />
      <!-- 收缩 -->
      <img
        src="@/assets/images/image_qjsm_sq.png"
        alt=""
        class="qjsm_sq"
        @click="modeldes = ''"
      />
      <!-- 背景 -->
      <img src="@/assets/images/image_qjsm_bg.png" alt="" class="qjsm_bg" />
      <!--标题 -->
      <img
        src="@/assets/images/image_qjsm_title.png"
        alt=""
        class="qjsm_title"
      />
      <!-- 主体内容-->
      <div v-html="modeldes" class="modeldesmain beautifulScroll"></div>
    </div>
    <!-- 模型介绍收拾 -->
    <img
      v-show="!modeldes"
      src="@/assets/images/image_qjsm_zk.png"
      alt=""
      class="qjsm_zk"
      @click="checkeddes()"
    />
  </div>
</template>

<script>
import { selectVrModelDetail, updateVrModelComponent } from '@/api/model.js'
import moDelType from '../glbadmin/moDelType.vue'
import * as THREE from 'three'
export default {
  name: 'WorkspaceJsonIndex',
  components: {
    moDelType
  },

  mounted() {
    // 添加鼠标滚轮事件监听
    // 确保引用存在
    if (this.$refs.modelbox && this.$refs.modelbox.$el) {
      this.$refs.modelbox.$el.addEventListener('wheel', this.handleMouseWheel)
    }
    // 添加键盘事件监听
    window.addEventListener('keydown', this.handleKeyDown)

    // 初始化 flexible
    // this.flexible()
  },

  beforeDestroy() {
    // 移除键盘事件监听
    window.removeEventListener('keydown', this.handleKeyDown)
  },

  methods: {
    flexible() {
      const docEl = document.documentElement
      const metaEl = document.querySelector('meta[name="viewport"]')
      const dpr = window.devicePixelRatio || 1
      let scale = 1 / dpr

      // 设置 viewport 缩放比例
      if (!metaEl) {
        metaEl = document.createElement('meta')
        metaEl.setAttribute('name', 'viewport')
        metaEl.setAttribute(
          'content',
          `width=device-width, initial-scale=${scale}, maximum-scale=${scale}, minimum-scale=${scale}, user-scalable=no`
        )
        docEl.firstElementChild.appendChild(metaEl)
      } else {
        metaEl.setAttribute(
          'content',
          `width=device-width, initial-scale=${scale}, maximum-scale=${scale}, minimum-scale=${scale}, user-scalable=no`
        )
      }

      // 设置 data-dpr 属性，用于 CSS 中区分不同 dpr 设备
      docEl.setAttribute('data-dpr', dpr)

      // 设置根元素字体大小（这里可以根据需要调整）
      docEl.style.fontSize = 100 * (docEl.clientWidth / 750) + 'px'

      // 页面尺寸变化时重置根元素字体大小
      window.addEventListener('resize', () => {
        docEl.style.fontSize = 100 * (docEl.clientWidth / 750) + 'px'
      })
      window.addEventListener('pageshow', e => {
        if (e.persisted) {
          docEl.style.fontSize = 100 * (docEl.clientWidth / 750) + 'px'
        }
      })
    },
    handleKeyDown(event) {
      if (event.key == 'Escape' && this.fullscreen) {
        this.fullscreen = false
      }
    },
    taskidgo(item) {
      this.taskid = item.componentSign
      // console.log('当前标识', item.componentSign, this.taskid)

      this.modeldes = item.componentInfo
      // 遍历 modelDrag 数据，检查是否存在 name == item.componentSign 的对象
      this.$refs.modelbox.outlinePass.selectedObjects = []
      this.$refs.modelbox.model.traverse(child => {
        if (child.name == item.componentSign) {
          this.$refs.modelbox.outlinePass.selectedObjects.push(child)
          // this.$refs.modelbox.selectedObject = child
        }
      })
    },
    assemble() {
      this.chajie = false
      this.$refs.modelbox.resetModel()
    },
    disassemble() {
      console.log('执行了拆解')

      this.chajie = true
      this.$refs.modelbox.mergeHandle()
    },
    checkedModel(checkedModel) {
      this.taskid = checkedModel.name
      //
      this.checkeddes()
    },
    checkeddes() {
      const selectedItem = this.modelDrag.find(
        item => item.componentSign == this.taskid
      )
      if (selectedItem) {
        this.modeldes = selectedItem.componentInfo
      } else {
        this.modeldes = this.newdata.componentInfo
      }
    },
    zoomIn() {
      const camera = this.$refs.modelbox.getCamera()
      camera.zoom += 0.1
      camera.updateProjectionMatrix()
    },
    zoomOut() {
      const camera = this.$refs.modelbox.getCamera()
      camera.zoom -= 0.1
      camera.updateProjectionMatrix()
    },
    handleMouseWheel(event) {
      const camera = this.$refs.modelbox.getCamera()
      if (event.deltaY < 0) {
        camera.zoom += 0.1
      } else {
        camera.zoom -= 0.1
      }
      camera.updateProjectionMatrix()
    },
    toggleFullscreen() {
      let docElm = document.querySelector('#app')
      this.fullscreen = !this.fullscreen
      if (this.fullscreen) {
        if (docElm.requestFullscreen) {
          docElm.requestFullscreen()
        } else if (docElm.msRequestFullscreen) {
          docElm.msRequestFullscreen()
        } else if (docElm.mozRequestFullScreen) {
          docElm.mozRequestFullScreen()
        } else if (docElm.webkitRequestFullScreen) {
          docElm.webkitRequestFullScreen()
        }
      } else {
        if (document.exitFullscreen) {
          document.exitFullscreen()
        } else if (document.msExitFullscreen) {
          document.msExitFullscreen()
        } else if (document.mozCancelFullScreen) {
          document.mozCancelFullScreen()
        } else if (document.webkitCancelFullScreen) {
          document.webkitCancelFullScreen()
        }
      }
    },
    showSelectedModel() {
      const selectedItem = this.modelDrag.find(
        item => item.componentSign == this.taskid
      )
      if (!selectedItem) {
        console.log('模型不存在于 modelDrag 中', this.taskid)
        return
      }

      const visibleIds = this.modelDrag.map(item => item.componentSign)

      if (!this.showSelectedModelshow) {
        this.mentbjs = '独显'
        this.$refs.modelbox.model.traverse(child => {
          if (visibleIds.includes(child.name)) {
            if (child.name == this.taskid) {
              child.visible = true

              // console.log('修改前位置', child.position)
              // child.position.set(1, 1, 1) // 将选中的模型坐标设置为原点
              // console.log('当前位置', child.position)
              const boundingBox = new THREE.Box3().setFromObject(child)
              const target = boundingBox.getCenter(new THREE.Vector3())
              const fov = this.$refs.modelbox.camera.fov * (Math.PI / 180)
              this.modelSize = boundingBox.getSize(new THREE.Vector3()).length()
              const cameraDistance =
                this.modelSize / (2 * Math.tan(fov / 2)) + 0.5
              this.$refs.modelbox.camera.position.set(
                target.x,
                target.y,
                target.z + cameraDistance
              )
              this.$refs.modelbox.camera.lookAt(target)
            } else {
              child.visible = false
            }
          }
        })

        this.showSelectedModelshow = true
      } else {
        this.$refs.modelbox.model.traverse(child => {
          if (visibleIds.includes(child.name)) {
            child.visible = true
          }
        })
        const boundingBox = new THREE.Box3().setFromObject(
          this.$refs.modelbox.model
        )
        const target = boundingBox.getCenter(new THREE.Vector3())
        const fov = this.$refs.modelbox.camera.fov * (Math.PI / 180)
        this.modelSize = boundingBox.getSize(new THREE.Vector3()).length()
        const cameraDistance = this.modelSize / (2 * Math.tan(fov / 2)) + 0.5
        this.$refs.modelbox.camera.position.set(
          target.x,
          target.y,
          target.z + cameraDistance
        )
        this.$refs.modelbox.camera.lookAt(target)
        this.showSelectedModelshow = false
      }
    },
    toggleRotation() {
      if (this.rotationInterval) {
        clearInterval(this.rotationInterval)
        this.rotationInterval = null
        // 恢复模型到原始位置
        if (this.originalRotation) {
          this.$refs.modelbox.model.rotation.copy(this.originalRotation)
        }
      } else {
        // 存储模型的原始位置
        this.originalRotation = this.$refs.modelbox.model.rotation.clone()
        this.rotationInterval = setInterval(() => {
          this.$refs.modelbox.model.rotation.y += 0.01
        }, 16)
      }
    },
    mentfn(id) {
      const actions = {
        1: () => {
          this.tipshow = !this.tipshow
          this.mentid = id
        },
        2: () => {
          this.toggleFullscreen()
          this.mentid = id
        },
        3: () => {
          this.zoomOut()
          this.mentid = id
        },
        4: () => {
          this.zoomIn()
          this.mentid = id
        },
        5: () => {
          if (!this.chajie) {
            this.$message({
              message: '当前已是组合状态',
              type: 'warning'
            })
            return
          }
          if (this.showSelectedModelshow) {
            this.$message({
              message: '请先关闭单独显示某个组件',
              type: 'warning'
            })
            return
          }
          this.assemble()
          this.mentid = id
        },
        6: () => {
          if (this.showSelectedModelshow) {
            this.$message({
              message: '请先关闭单独显示某个组件',
              type: 'warning'
            })
            return
          }
          if (this.chajie) {
            this.$message({
              message: '当前已是拆解状态，无法继续拆解',
              type: 'warning'
            })
            return
          }
          this.disassemble()
          this.mentid = id
        },
        7: () => {
          if (!this.taskid) {
            this.$message({
              message: '请先选择一个模型',
              type: 'warning'
            })
            return
          }
          this.showSelectedModel()
          this.mentid = id
        },
        8: () => {
          this.toggleRotation()
          this.mentid = id
        }
      }

      if (actions[id]) {
        actions[id]()
      }
    }
  },
  data() {
    return {
      //
      chajie: false,
      mentid: 1,
      fullscreen: false,
      taskshow: true,
      tipshow: false,
      modeldes: '',
      newdata: null,
      taskid: '',
      modelUrl: '',
      baseurl: 'http://zfatt.oss-cn-beijing.aliyuncs.com/',
      modelDrag: [],
      showSelectedModelshow: false,
      rotationInterval: null,
      mentdata: [
        {
          id: 1,
          name: '帮助提示',
          nameac: '帮助提示',
          src: require('@/assets/images/image_ts_sel.png'),
          srcac: require('@/assets/images/image_ts_nor.png')
        },
        {
          id: 2,
          name: '全屏',
          nameac: '全屏',
          src: require('@/assets/images/image_icon_quanping_sel.png'),
          srcac: require('@/assets/images/image_icon_quanping_nor.png')
        },
        {
          id: 3,
          name: '缩小',
          nameac: '缩小',
          src: require('@/assets/images/image_icon_suoxiao-sel.png'),
          srcac: require('@/assets/images/image_icon_suoxiao-nor.png')
        },
        {
          id: 4,
          name: '放大',
          nameac: '放大',
          src: require('@/assets/images/image_icon_fangda-sel.png'),
          srcac: require('@/assets/images/image_icon_fangda-nor.png')
        },
        {
          id: 5,
          name: '组合',
          nameac: '组合',
          src: require('@/assets/images/image_icon_zhengti_sel.png'),
          srcac: require('@/assets/images/image_icon_zhengti_nor.png')
        },
        {
          id: 6,
          name: '拆解',
          nameac: '拆解',
          src: require('@/assets/images/image_icon_chaifen_sel.png'),
          srcac: require('@/assets/images/image_icon_chaifen_nor.png')
        },
        {
          id: 7,
          name: '独显',
          nameac: '独显',
          src: require('@/assets/images/image_icon_dandu_sel.png'),
          srcac: require('@/assets/images/image_icon_dandu_nor.png')
        },
        {
          id: 8,
          name: '旋转',
          nameac: '旋转 ',
          src: require('@/assets/images/image_icon_xuanzhuan_nor.png'),
          srcac: require('@/assets/images/image_icon_xuanzhuan_sel.png')
        }
      ]
    }
  },
  created() {
    const data = JSON.parse(this.$route.query.data)
    console.log('当前数据', data)

    selectVrModelDetail({ vrModelId: data.vrModelId }).then(res => {
      if (res.code == '200') {
        this.$message({
          message: '查询成功',
          type: 'success'
        })

        this.modelDrag = res.data.vrModelComponentDtoList
        this.newdata = res.data
        this.modelUrl = res.data.modelUrl
      } else {
        this.$message({
          message: res.message,
          type: 'error'
        })
      }
    })
  }
}
</script>

<style scoped>
.mainbox {
  width: 100%;
  height: 100%;
}
.anbox {
  position: absolute;
  bottom: 5px;
  left: 50%;
  transform: translate(-50%, 0);
  display: flex;
  justify-content: center;
  align-items: center;
}

.taskbox {
  position: absolute;
  top: 50%;
  left: 20px;
  transform: translate(0, -50%);
}

.image_qj_bg {
  width: 185px;
  height: 710px;
  position: relative;
}
.taskmain {
  position: absolute;
  top: 60px;
  left: 1px;
  height: 620px;
  width: 97%;
  overflow: hidden;
  overflow-y: auto;
  display: flex;
  flex-wrap: wrap;
  padding: 15px 0;
  padding-top: 0px;
}
.taskitem {
  margin: 5px 0px;
  margin-left: 20px;
}

.taskitem-nameac {
  cursor: pointer;
  color: aqua;
  background-color: #ffa7a7;
}
.modeldesbox {
  position: absolute;
  right: 25px;
  top: 50%;
  transform: translate(0%, -50%);
  /* -webkit-animation: fadeInRightBig 1s 0.2s ease both;
  -moz-animation: fadeInRightBig 1s 0.2s ease both; */
}
.modeldesbox div {
  font-size: 24px;
  color: #ffffff;
}
.indexbg {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
  z-index: -1;
}
.head_titlebox {
  position: absolute;
  top: 0;
  left: 50%;
  transform: translate(-50%, 0);
  font-size: 24px;
  color: #ffffff;
  width: 100%;
  height: 120px;
}
.head_title {
  width: 100%;
  height: 120px;
  position: absolute;
}
.head_titlebox span {
  font-size: 48px;
  color: #ffffff;
  font-weight: 800;
  display: block;
  width: 500px;
  height: 120px;
  text-align: center;
  line-height: 120px;
  position: relative;
  left: 50%;
  overflow: hidden;
  transform: translate(-50%, 0);
}
.footer {
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translate(-50%, 0);
  width: 1920px;
  height: 40px;
}
.anboxitem {
  margin: 0px 10px;
}
.caozuotishi {
  position: absolute;
  top: -198px;
  width: 352px;
  height: 194px;
}
.yiru_bg {
  position: absolute;
  top: -40px;
}
.yiru_bg img {
  width: 77px;
  height: 40px;
}
.yiru_bg span {
  font-size: 14px;
  color: #ffffff;
  position: absolute;
  left: 50%;
  top: 40%;
  transform: translate(-50%, -50%);
  display: block;
}
.boder_zuo {
  position: absolute;
  top: 50%;
  left: 0px;
  transform: translate(0%, -50%);
  width: 70px;
  height: 820px;
}
.boder_you {
  position: absolute;
  top: 50%;
  right: 0px;
  transform: translate(0%, -50%);
  width: 70px;
  height: 820px;
}
.qjsm_zk {
  width: 70px;
  height: 180px;
  position: absolute;
  top: 50%;
  right: 0px;
  transform: translate(0%, -50%);
  cursor: pointer;
}
.qjsm_bg {
  width: 346px;
  height: 713px;
}
.icon_close {
  width: 36px;
  height: 36px;
  position: absolute;
  top: -18px;
  right: -18px;
  cursor: pointer;
  z-inex: 999;
}
.qjsm_sq {
  width: 44px;
  height: 44px;
  position: absolute;
  top: 12px;
  left: -22px;
  cursor: pointer;
  z-index: 9999;
}
.qjsm_title {
  position: absolute;
  left: 0px;
  width: 370px;
  height: 70px;
}
.modeldesmain {
  width: 340px;
  padding: 0px 20px;
  height: 620px;
  position: absolute;
  left: 50%;
  top: 75px;
  transform: translate(-50%, 0);
  overflow-y: auto;
}
.taskitem-iconbox {
  position: relative;
}
.taskitem-iconbox img {
  width: 137px;
  height: 115px;
  overflow: hidden;
  /* object-fit: contain;  */
}
.taskitem-name {
  cursor: pointer;
  position: absolute;
  left: 50%;
  bottom: 0;
  transform: translate(-50%, 0);
}
.taskitem-name img {
  width: 108px;
  height: 27px;
}
.taskitem-name span {
  width: 98px;
  height: 27px;
  display: block;
  font-weight: 800;
  font-size: 14px;
  color: #ffffff;
  position: absolute;
  text-align: center;
  line-height: 27px;
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
  padding: 0px 10px;
}
.image_icon_zk {
  position: absolute;
  left: -18px;
  top: 10px;
  width: 36px;
  height: 36px;
  z-index: 99;
  cursor: pointer;
  transform: rotate(180deg);
}
.quanping_icon_close {
  position: absolute;
  top: 48px;
  left: 50%;
  transform: translate(-50%, 0);
  width: 60px;
  height: 60px;
  cursor: pointer;
}
.image_qj_sqbox {
  width: 279px;
  height: 36px;
  position: absolute;
  left: 5px;
  top: 115px;
  cursor: pointer;
}
.image_qj_sq {
  width: 200px;
  height: 40px;
  position: absolute;
}
.image_qj_sqbox span {
  position: absolute;
  font-size: 22px;
  font-weight: 800;
  color: #ffffff;
  display: block;
  text-align: center;
  width: 200px;
  height: 40px;
  line-height: 40px;
}
@-webkit-keyframes fadeInRightBig {
  0% {
    opacity: 0;
    right: 0;
  }
  100% {
    opacity: 1;
    right: 80px;
  }
}
@-moz-keyframes fadeInRightBig {
  0% {
    opacity: 0;
    right: 0;
  }
  100% {
    opacity: 1;
    right: 80px;
  }
}
.taskitem-icon {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  cursor: pointer;
  width: 110px !important;
  height: 80% !important;
  object-fit: contain; /* 或者使用 object-fit: cover; */
}
/* 封装公共按钮类 */
.tool {
  display: flex;
  justify-content: center;
  align-items: center;
}
.tool img.active {
  cursor: pointer;
  display: none;
}

.tool:hover img.normal,
.tool.active img.normal {
  display: none;
}

.tool:hover img.active,
.tool.active img.active {
  display: block;
}
.tool .tiptool {
  display: none;
}

.tool:hover .tiptool {
  display: block;
}
.yiru_bg span {
  display: block;

  width: 75px;
  text-align: center;
  overflow: hidden;
  font-size: 15px;
}
.qjname {
  position: absolute;
  top: 10px;
  left: 0px;
  width: 185px;
  height: 45px;
}
.image_qj_title {
  position: absolute;
  left: 0px;
}
.qjname span {
  font-size: 22px;
  font-weight: 800;
  color: #ffffff;
  display: block;

  text-align: center;
}
.image_icon_zks {
  position: absolute;
  left: 0;
  top: 0px;
  width: 36px;
  height: 36px;
  z-index: 99;
  cursor: pointer;
}
/* 滚动条美化 */
.beautifulScroll::-webkit-scrollbar {
  width: 5px;
  height: 5px;
  background: #2b4c86;
  border-radius: 5px;
}

.beautifulScroll::-webkit-scrollbar-track {
  background: #2b4c86;
  border-radius: 5px;
}

.beautifulScroll::-webkit-scrollbar-thumb {
  border-radius: 5px;
  background: #4180f5;
}
.mentbjs {
  position: absolute;
  bottom: 2px;
  width: 884px;
  height: 49px;
  z-index: -1;
}
</style>
